﻿using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace XFGameFramework
{ 
    public class ListenerInitOnLoad
    {

        [UnityEditor.InitializeOnLoadMethod]
        private static void InitOnLoad()
        {
            GenerateCanvas();
            GenerateEventSystem();
            LogUtilInit.InitOnLoad();
        }

        // 生成Canvas预制体
        private static void GenerateCanvas()
        {
            string canvas_path = "Assets/Resources/XFGameFramework/Canvas.prefab";
            if (AssetDatabase.LoadAssetAtPath<GameObject>(canvas_path) != null) return;

            string dir = System.IO.Path.GetDirectoryName(canvas_path);
            if (!System.IO.Directory.Exists(dir))
                System.IO.Directory.CreateDirectory(dir);

            GameObject canvas = new GameObject("Canvas");

            Canvas c = canvas.AddComponent<Canvas>();
            c.renderMode = RenderMode.ScreenSpaceOverlay;


            CanvasScaler scaler = canvas.AddComponent<CanvasScaler>();
            scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
            scaler.referenceResolution = new Vector2(1920, 1080); // 默认值
            scaler.matchWidthOrHeight = 1; // 横屏以高进行适配

            GraphicRaycaster raycaster = canvas.AddComponent<GraphicRaycaster>();

            canvas.AddComponent<AutomaticAdaptationCanvasScaler>();

            PrefabUtility.SaveAsPrefabAsset(canvas, canvas_path);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            GameObject.DestroyImmediate(canvas);
             
        }
         
        private static void GenerateEventSystem()
        {
            string event_system_path = "Assets/Resources/XFGameFramework/EventSystem.prefab";
            if (AssetDatabase.LoadAssetAtPath<GameObject>(event_system_path) != null) return;

            string dir = System.IO.Path.GetDirectoryName(event_system_path);
            if (!System.IO.Directory.Exists(dir))
                System.IO.Directory.CreateDirectory(dir);

            GameObject eventSystem = new GameObject("EventSystem");

            EventSystem e = eventSystem.AddComponent<EventSystem>();

            eventSystem.AddComponent<StandaloneInputModule>();

            PrefabUtility.SaveAsPrefabAsset(eventSystem, event_system_path);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            GameObject.DestroyImmediate(eventSystem);
        }
         

    }
}


